<?php
/**********************************************************************
 *
 * $Id: kaPDF.php,v 1.2 2006/06/19 15:37:42 lbecchi Exp $
 *
 * purpose: Allow user upload custom SHP file to embrio interface
 *
 * author: Lorenzo Becchi and Luca Casagrande
 *
 * NOTE:
 * This file will allow user to upload a zip file that contains all part of a SHP Vector file.
 * Once the form is being submitted, the zip is extracted  and pywps is called and the vector 
 * file is inported inside GRASS.
 * We use the history.xml to store all the files that are imported in this way. If you create a script
 * that delete/rename files, remember to update also this one-
 * TODO:
 * - Change the simplexml part in DOM to allow support for most php version
 * -
 * - 
 *
 **********************************************************************
 *
 * Copyright (c)  2006, ominiverdi.org
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 **********************************************************************/

$import = simplexml_load_file('../history.xml');

//First of all, we wait that the user submit the form

if (isset($_POST['submit']))
    	
	{
//NAME CHECK: Check that the name is not yet used

$children = $import->children();
	foreach($children AS $child) {
		if ($child['name']==$_POST['name']) {
		$result=0;
		print ('<p>The name already exist<p>');
		break;
		}else{
		$result=1;
		}
		}

//Input are all set. Now check if the user submitted a valid ZIP

if ($result !=0) {

/* Set a few constants */
define ("FILEREPOSITORY","/var/www/localhost/htdocs/tmp/");
/* Make sure that the file was POSTed. */
if (is_uploaded_file($_FILES['shape']['tmp_name'])) {
      echo$_FILES['shape']['type'];
      //die();
      /* Is the file a Zip file? */
      if ($_FILES['shape']['type'] = "application/zip" OR $_FILES['shape']['type'] = "application/x-compressed" OR $_FILES['shape']['type'] = "application/x-zip-compressed" OR $_FILES['shape']['type'] = "multipart/x-zip"  ) {
           
	   $name = $_POST['name'];
	   $description=$_POST['description'];
           $result = move_uploaded_file($_FILES['shape']['tmp_name'],
           FILEREPOSITORY."/$name.zip");
	                if ($result == 1) { 
			echo "<p>File successfully uploaded.</p>";
			}
               else echo "<p>There was a problem uploading the file.</p>";
      }
	else {
           echo "<p>The vector file should be uploaded in zip format</p>";

     }
}

if ($result ==1) 
{ 
$path=FILEREPOSITORY."/$name.zip";
/*
$za = new ZipArchive();
$path=FILEREPOSITORY."/$name.zip";
$za->open($path);
 
echo("<p> The archives contains those files:<p>");

for ($i=0; $i<$za->numFiles;$i++) {
      $shape=$za->statIndex($i);
      $file=$shape[name];
      print ($file."\n");
      }
 
 
 
 echo("<p>Now start to check if uploaded file is ok...</p>");
 /* Here we check it the zip file is correct 

//Check it the zip file contains at least one shape file
for ($i=0; $i<$za->numFiles;$i++) {
      $shape=$za->statIndex($i);
      $file=$shape[name];
      $filename = explode(".", $file);
	if ($filename[1] =='shp') {
			$shapename=$filename[0];
			$shapenumber++;
	}
       }
if ($shapename==NULL) {
	echo ("There are no file shp in the archives");
   } else if ( $shapenumber > 1)
   {
   echo("There is more then one shape file..Please check it out");
   } else{
   echo $shapename, ".shp is the file that will be imported inside GRASS.";
   }

//Check that all the files belong to the same shape file

for ($i=0; $i<$za->numFiles;$i++) {
      $shape=$za->statIndex($i);
      $file=$shape[name];
      $filename = explode(".", $file);
	if ($filename[0] !=$shapename) {
		echo ("The archives contains files from different sources.Please check it out");
	break;
	} 
       }
*/
//Now start the unzip process
   $tmp_dir = sprintf("%0.6d",rand(0,999999));
   $dir='/var/www/localhost/htdocs/tmp/'.$tmp_dir."/";
   mkdir($dir);
   $zip = zip_open($path);
   while($zip_entry = zip_read($zip)) {
       $entry = zip_entry_open($zip,$zip_entry);
       $filename = zip_entry_name($zip_entry);
       $target_dir = $dir.substr($filename,0,strrpos($filename,'/'));
       $filesize = zip_entry_filesize($zip_entry);
       if (is_dir($target_dir) || mkdir($target_dir)) {
           if ($filesize > 0) {
               $contents = zip_entry_read($zip_entry, $filesize);
               file_put_contents($dir.$filename,$contents);
           }
       }
   }
/*//Now we can add information to the hystory file
$vector = $import->addChild('vector');
$vector->addAttribute('name', $name);
//$vector->addAttribute('description',$description);
file_put_contents('../history.xml', $import->asXML());
//Show the new history file

$shp=$dir.$shapename.".shp";
$shx=$dir.$shapename.".shx";
$dbf=$dir.$shapename.".dbf";

$stringa_query = "http://gentoobox.homedns.org/cgi-bin/wps.py?service=wps&version=0.4.0&request=Execute&Identifier=fileimport&";
$array = array('shp', $shp,'shx',$shx,'dbf', $dbf,'name',$name);
$comma_separated = implode(",", $array);
$stringa_query .= "datainputs=";
$stringa_query .= $comma_separated;
$stringa_query .= "&status=true&store=true";
//var_dump($stringa_query);
//die();
$dom = new DOMDocument();
$dom->load($stringa_query);
//$CVR = $dom->getElementsByTagName('ComplexValueReference');
//$nodo = $CVR->item(0)->getAttribute('reference');
*/
echo ('<p><A HREF="http://gentoobox.homedns.org/test/moduli/import/v_buffer_vect.php ">Procede to the buffer section</A></p>');

}
}
}
?> 